package com.yueya.basic.dict.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.jfinal.kit.JsonKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.yueya.basic.dict.model.Dict;
import com.yueya.common.model.ComboBox;

public class DictService {


	public Page<Dict> paginate(int pageNum, int pageSize, Map<String,Object> map) {

		String sql_from = "select   * ";

		StringBuffer sb = new StringBuffer(" from  t_dict where 1=1   ");
		Page<Dict> page = null;

		if (map.get("name") != null && !"".equals(map.get("name"))) {
			sb.append(" and (category like '%" + map.get("name")
					+ "%' or dict_name like '%" + map.get("name") + "%')");
		}
		sb.append(" order by category asc, order_id asc ");
		page = Dict.dao.paginate(pageNum, pageSize, sql_from, sb.toString());
		return page;
	}

	public List<Record> getValues(String type) {
		String sql = "select * from t_dict where category = '" + type
				+ "' order by dict_value asc";
		return Db.find(sql);
	}
	
	public List<Record> getValuesOrder(String category) {
		if(StrKit.isBlank(category))	return new ArrayList<Record>();
		return Db.find("SELECT * FROM t_dict WHERE category=? ORDER BY order_id ASC", category);
	}

	public String getJsonValues(String type) {
		List<Record> list = Dict.service.getValues(type);
		List<ComboBox> datalist = new ArrayList<ComboBox>();
		if (list != null && list.size() > 0) {
			Record r = null;
			ComboBox cb = null;
			for (int i = 0; i < list.size(); i++) {
				r = list.get(i);
				cb = new ComboBox();
				cb.setId(r.getStr("dict_value"));
				cb.setText(r.getStr("dict_name"));
				cb.setDesc(r.getStr("category"));
				datalist.add(cb);
			}
		}
		return JsonKit.toJson(datalist);
	}

	public Dict getDictByCategoryAndName(String category, String name) {

		Dict dict = Dict.dao.findFirst(
				"select * from t_dict where category =? and dict_name =? ",
				category, name);

		return dict;

	}
	
	public Dict getDictByCategoryAndValue(String category, String value) {

		Dict dict = Dict.dao.findFirst(
				"select * from t_dict where category =? and value =? ",
				category, value);

		return dict;

	}

	// 按value排序
	public List<Record> getValuesOrderByValue(String type) {
		String sql = "select * from t_dict where category = '" + type
				+ "' order by value";
		return Db.find(sql);
	}
}
